package work.sajor.wechatpush.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {


    public static final String YYYY_MM_DD = "yyyy-MM-dd";

    public static SimpleDateFormat getSimpleDateFormat() {
        return new SimpleDateFormat(YYYY_MM_DD);
    }


    public static int getAnniversary(String anniversary) {
        return after(anniversary);
    }

    public static int getBirthday(String birthday){
        return before(birthday);
    }

    /**
     * 距离date还有多少天
     * @param date
     * @return
     */
    public static int before(String date) {
        int day = 0;
        try {
            long time = getSimpleDateFormat().parse(date).getTime() - System.currentTimeMillis();
            day = (int) (time / 86400000L);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return day;
    }


    /**
     * 已经过去date多少天
     * @param date
     * @return
     */
    public static int after(String date) {
        int day = 0;
        try {
            long time = System.currentTimeMillis() - getSimpleDateFormat().parse(date).getTime();
            day = (int) (time / 86400000L);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return day;
    }


    /**
     * 获取指定日期的农历日期
     * @param date 日期字符串 (格式: yyyy-MM-dd)
     * @return 农历日期字符串
     */
    public static String getLunarDate(String date) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date d = sdf.parse(date);
            return getLunarDate(d);
        } catch (ParseException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 获取指定日期的农历日期
     * @param date 日期对象
     * @return 农历日期字符串
     */
    public static String getLunarDate(Date date) {
        ChineseCalendar cc = new ChineseCalendar(date);
        return cc.getChineseMonth() + cc.getChineseDay();
    }

    /**
     * 计算距离指定农历日期还有多少天
     * 如果今年的该农历日期已过，则计算到明年该农历日期的天数
     * 如果今年的该农历日期未过，则计算到今年该农历日期的天数
     * @param lunarDate 农历日期字符串，格式为"MMDD"，如"0202"表示农历二月初二
     * @return 距离该农历日期的天数
     */
    public static int daysUntilLunarDate(String lunarDate) {
        try {
            // 解析输入的农历日期
            int month = Integer.parseInt(lunarDate.substring(0, 2));
            int day = Integer.parseInt(lunarDate.substring(2, 4));

            // 获取当前年份
            Calendar now = Calendar.getInstance();
            int currentYear = now.get(Calendar.YEAR);

            // 获取今年的该农历日期对应的阳历日期
            ChineseCalendar thisYearLunar = new ChineseCalendar(currentYear, month, day);
            Date thisYearDate = thisYearLunar.getGregorianDate();

            // 如果今年的该农历日期已过，则计算到明年的该农历日期
            if (thisYearDate.before(now.getTime())) {
                // 获取明年的该农历日期对应的阳历日期
                ChineseCalendar nextYearLunar = new ChineseCalendar(currentYear + 1, month, day);
                Date nextYearDate = nextYearLunar.getGregorianDate();

                // 计算天数差
                long diff = nextYearDate.getTime() - now.getTimeInMillis();
                return (int) (diff / (24 * 60 * 60 * 1000));
            } else {
                // 计算到今年该农历日期的天数差
                long diff = thisYearDate.getTime() - now.getTimeInMillis();
                return (int) (diff / (24 * 60 * 60 * 1000));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * 中国农历类
     */
    static class ChineseCalendar {
        private int year;
        private int month;
        private int day;
        private boolean leap;

        // 农历数据表，存储各年份的农历信息
        final static long[] LUNAR_INFO = {
                0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2,
                0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0, 0x14977,
                0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970,
                0x06566, 0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950,
                0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557,
                0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5d0, 0x14573, 0x052d0, 0x0a9a8, 0x0e950, 0x06aa0,
                0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, 0x0f263, 0x0d950, 0x05b57, 0x056a0,
                0x096d0, 0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b5a0, 0x195a6,
                0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, 0x0ab60, 0x09570,
                0x04af5, 0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, 0x055c0, 0x0ab60, 0x096d5, 0x092e0,
                0x0c960, 0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5,
                0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930,
                0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65, 0x0d530,
                0x05aa0, 0x076a3, 0x096d0, 0x04bd7, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520, 0x0dd45,
                0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0
        };

        // 天干
        private static final String[] TIANGAN = {
                "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"
        };

        // 地支
        private static final String[] DEZHI = {
                "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"
        };

        // 生肖
        private static final String[] ANIMALS = {
                "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"
        };

        // 农历月份
        private static final String[] MONTHS = {
                "正月", "二月", "三月", "四月", "五月", "六月",
                "七月", "八月", "九月", "十月", "冬月", "腊月"
        };

        // 农历日期
        private static final String[] DAYS = {
                "初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十",
                "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十",
                "廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十"
        };

        /**
         * 构造函数，根据公历日期初始化农历日期
         * @param date 公历日期
         */
        public ChineseCalendar(Date date) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateString = sdf.format(date);
            String[] parts = dateString.split("-");
            int year = Integer.parseInt(parts[0]);
            int month = Integer.parseInt(parts[1]);
            int day = Integer.parseInt(parts[2]);
            init(year, month, day);
        }

        /**
         * 构造函数，根据农历年月日初始化
         * @param lunarYear 农历年
         * @param lunarMonth 农历月
         * @param lunarDay 农历日
         */
        public ChineseCalendar(int lunarYear, int lunarMonth, int lunarDay) {
            initByLunar(lunarYear, lunarMonth, lunarDay, false);
        }

        /**
         * 构造函数，根据农历年月日和是否闰月初始化
         * @param lunarYear 农历年
         * @param lunarMonth 农历月
         * @param lunarDay 农历日
         * @param isLeapMonth 是否闰月
         */
        public ChineseCalendar(int lunarYear, int lunarMonth, int lunarDay, boolean isLeapMonth) {
            initByLunar(lunarYear, lunarMonth, lunarDay, isLeapMonth);
        }

        /**
         * 初始化农历日期
         * @param gy 公历年
         * @param gm 公历月
         * @param gd 公历日
         */
        private void init(int gy, int gm, int gd) {
            int i, leap = 0, temp = 0, offset = 0;
            Date baseDate = new Date(1900 - 1900, 0, 31); // 1900年1月31日为基准日期
            Date objDate = new Date(gy - 1900, gm - 1, gd);
            offset = (int) ((objDate.getTime() - baseDate.getTime()) / 86400000L);

            // 计算农历年份
            for (i = 1900; i < 2100 && offset > 0; i++) {
                temp = lYearDays(i);
                offset -= temp;
            }
            if (offset < 0) {
                offset += temp;
                i--;
            }

            this.year = i;
            leap = leapMonth(i); // 闰哪个月
            this.leap = false;

            // 计算农历月份
            for (i = 1; i < 13 && offset > 0; i++) {
                // 闰月
                if (leap > 0 && i == (leap + 1) && !this.leap) {
                    --i;
                    this.leap = true;
                    temp = leapDays(this.year);
                } else {
                    temp = monthDays(this.year, i);
                }

                // 解除闰月
                if (this.leap && i == (leap + 1)) {
                    this.leap = false;
                }
                offset -= temp;
            }

            if (offset == 0 && leap > 0 && i == leap + 1) {
                if (this.leap) {
                    this.leap = false;
                } else {
                    this.leap = true;
                    --i;
                }
            }
            if (offset < 0) {
                offset += temp;
                --i;
            }

            this.month = i;
            this.day = offset + 1;
        }

        /**
         * 根据农历日期初始化
         * @param lunarYear 农历年
         * @param lunarMonth 农历月
         * @param lunarDay 农历日
         * @param isLeapMonth 是否闰月
         */
        private void initByLunar(int lunarYear, int lunarMonth, int lunarDay, boolean isLeapMonth) {
            this.year = lunarYear;
            this.month = lunarMonth;
            this.day = lunarDay;
            this.leap = isLeapMonth;
        }

        /**
         * 获取对应的公历日期
         * @return 公历日期
         */
        public Date getGregorianDate() {
            // 计算农历日期距离1900年1月31日有多少天
            int offset = 0;

            // 计算年份偏移
            for (int i = 1900; i < year; i++) {
                offset += lYearDays(i);
            }

            // 计算月份偏移
            for (int i = 1; i < month; i++) {
                offset += monthDays(year, i);
            }

            // 如果是闰月且月份大于闰月，则需要加上闰月天数
            int leap = leapMonth(year);
            if (leap > 0 && month > leap) {
                offset += leapDays(year);
            }

            // 加上日期偏移
            offset += day - 1;

            // 计算公历日期
            Calendar cal = Calendar.getInstance();
            cal.set(1900, 0, 31); // 1900年1月31日
            cal.add(Calendar.DAY_OF_YEAR, offset);
            return cal.getTime();
        }

        /**
         * 获取农历年份的总天数
         * @param y 年份
         * @return 总天数
         */
        private int lYearDays(int y) {
            int i, sum = 348;
            for (i = 0x8000; i > 0x8; i >>= 1) {
                if ((LUNAR_INFO[y - 1900] & i) != 0) {
                    sum += 1;
                }
            }
            return sum + leapDays(y);
        }

        /**
         * 获取农历年份闰月的天数
         * @param y 年份
         * @return 闰月天数
         */
        private int leapDays(int y) {
            if (leapMonth(y) != 0) {
                return ((LUNAR_INFO[y - 1900] & 0x10000) != 0) ? 30 : 29;
            } else {
                return 0;
            }
        }

        /**
         * 获取农历年份闰哪个月
         * @param y 年份
         * @return 闰月月份，0表示没有闰月
         */
        private int leapMonth(int y) {
            return (int) (LUNAR_INFO[y - 1900] & 0xf);
        }

        /**
         * 获取农历年份某个月的天数
         * @param y 年份
         * @param m 月份
         * @return 该月天数
         */
        private int monthDays(int y, int m) {
            return ((LUNAR_INFO[y - 1900] & (0x10000 >> m)) != 0) ? 30 : 29;
        }

        /**
         * 获取农历月份名称
         * @return 月份名称
         */
        public String getChineseMonth() {
            if (leap) {
                return "闰" + MONTHS[month - 1];
            } else {
                return MONTHS[month - 1];
            }
        }

        /**
         * 获取农历日期名称
         * @return 日期名称
         */
        public String getChineseDay() {
            return DAYS[day - 1];
        }
    }
}
